import axios from 'axios';
import VueAxios from 'vue-axios';
import Vue from 'vue';
import { API_URL } from './config';

Vue.use(VueAxios, axios);

axios.defaults.withCredentials = true;

axios.defaults.retry = false; //重试次数
axios.defaults.retryCount = 1; //重试次数
axios.defaults.retryDelay = 1000; //重试延时

// 请求拦截器
axios.interceptors.request.use(
  // eslint-disable-next-line prettier/prettier
  function (config) {
    if (localStorage['token']) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers['token'] = localStorage['token'];
    }
    return config;
  },
  // eslint-disable-next-line prettier/prettier
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  err => {
    var config = err.config;
    // 判断是否配置了重试
    if (!config || !config.retry) return Promise.reject(err);

    // 设置重置次数，默认为0
    config.__retryCount = config.__retryCount || 0;

    // 判断是否超过了重试次数
    if (config.__retryCount >= config.retryCount) {
      return Promise.reject(err);
    }

    //重试次数自增
    config.__retryCount += 1;

    //延时处理
    // eslint-disable-next-line prettier/prettier
    var backoff = new Promise(function (resolve) {
      // eslint-disable-next-line prettier/prettier
      setTimeout(function () {
        resolve();
      }, config.retryDelay || 1);
    });

    //重新发起axios请求
    // eslint-disable-next-line prettier/prettier
    return backoff.then(function () {
      return axios(config);
    });
  }
);
/**
 * 封装axios的post请求
 *
 * @export
 * @param {*} url
 * @param {*} params
 * @param {*} retry   是否重试
 * @returns
 */
export function postDataBase(url, params, retry) {
  axios.defaults.retry = retry;
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        reject(error);
      });
  });
}
/**
 * 默认重试 post
 *
 * @export
 * @param {*} url
 * @param {*} params
 * @returns
 */
export function postDataRetry(url, params) {
  return postDataBase(url, params, true);
}

/**
 * 普通 post
 *
 * @export
 * @param {*} url
 * @param {*} params
 * @returns
 */
export function postData(url, params) {
  return postDataBase(url, params, false);
}

/**
 * 封装axios的get请求
 *
 * @export
 * @param {*} url
 * @param {*} params
 * @returns
 */
export function getDataBase(url, params, retry) {
  axios.defaults.retry = retry;
  return new Promise((resolve, reject) => {
    axios
      .get(url, { params: params })
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        reject(error);
      });
  });
}

/**
 * 默认重试 get
 *
 * @export
 * @param {*} url
 * @param {*} params
 * @returns
 */
export function getDataRetry(url, params) {
  axios.defaults.retry = true;
  return getDataBase(url, params, true);
}

/**
 * 普通 get
 *
 * @export
 * @param {*} url
 * @param {*} params
 * @returns
 */
export function getData(url, params) {
  axios.defaults.retry = false;
  return getDataBase(url, params, false);
}

export default {
  gologin(ourl) {
    // http://api.hangzhouhaiyu.com/api/member/weixin_login?h5_callback=
    let url = `${API_URL}/api/member/weixin_login?h5_callback=${encodeURIComponent(
      ourl
    )}`;
    window.location.href = url;
  },
  // 登录类型
  logintype(params) {
    return postData(`${API_URL}/api/member/login_type`, params);
  },
  // 登录
  login(params) {
    return postData(`${API_URL}/api/member/login`, params);
  },
  // 猫酷授权登录
  mallcoo_login(params) {
    return postData(`${API_URL}/api/member/mallcoo_login`, params);
  },
  gomallcoologin(activity_id, openid) {
    // http://api.hangzhouhaiyu.com/api/member/weixin_login?h5_callback=
    let url = `${API_URL}/api/member/mallcoo_login?open_id=${openid}&activity_id=${activity_id}&h5_callback=${encodeURIComponent(
      `https://m.hangzhouhaiyu.com/douwu/#/?activityid=${activity_id}`
    )}`;
    window.location.href = url;
  },
  // 发送短信验证码
  send_sms(params) {
    return postData(`${API_URL}/api/member/send_sms`, params);
  },
  // 用户信息
  userinfo(params) {
    return postData(`${API_URL}/api/member/info`, params);
  },
  // 活动详情
  activityinfo(params) {
    return postData(`${API_URL}/api/index/index`, params);
  },
  // 斗舞活动详情
  douwuinfo(params) {
    return getData(`${API_URL}/api/douwu/info`, params);
  },
  // 斗舞活动- 校验选择的队伍
  douwuCheckTeam(params) {
    return postData(`${API_URL}/api/douwu/check_team`, params);
  },
  // 斗舞活动-提交用户得分
  saveScore(params) {
    return postData(`${API_URL}/api/douwu/save_score`, params);
  },
  // 斗舞活动-请求开奖
  lottery(params) {
    return postData(`${API_URL}/api/douwu/lottery`, params);
  },
  // 斗舞活动-开奖结果
  resultList(params) {
    return postData(`${API_URL}/api/douwu/result_list`, params);
  },
  // 斗舞活动-当前活动实时结果
  progress(params) {
    return postData(`${API_URL}/api/douwu/progress`, params);
  },
  // 斗舞活动-当前活动数据
  progressInfo(params) {
    return getData(`${API_URL}/api/douwu/progress_info`, params);
  },
  // 大屏 - 上墙
  players(params) {
    return postData(`${API_URL}/api/large/players`, params);
  },
  // 大屏 - 排行榜
  rank(params) {
    return postData(`${API_URL}/api/large/rank`, params);
  },
  // 奖品列表
  prizelist(params) {
    return postData(`${API_URL}/api/large/prize`, params);
  },
  // 创建订单
  createOrder(params) {
    return postData(`${API_URL}/api/order/create`, params);
  },
  // 抽奖
  save_credit(params) {
    return postData(`${API_URL}/api/index/save_credit`, params);
  },
  // 抽奖
  save_credit_p(params) {
    return postData(`${API_URL}/api/puzzle/save_credit`, params);
  },
  // 抽奖记录
  record(params) {
    return postData(`${API_URL}/api/member/record`, params);
  },
  // 用户卷包列表
  couponList(params) {
    return postData(`${API_URL}/api/coupon/index`, params);
  },
  // 卷详情
  couponDetail(params) {
    return postData(`${API_URL}/api/coupon/detail`, params);
  },
  // 卷详情
  getOpenid(params) {
    return postData(`${API_URL}/api/order/open_id`, params);
  },
  // 商家登陆
  merchantLogin(params) {
    return postData(`${API_URL}/api/merchant/login`, params);
  },
  //优惠券核销
  verification(params) {
    return postData(`${API_URL}/api/merchant/verification`, params);
  },
  getPingActivityInfo(params) {
    return postData(`${API_URL}/api/puzzle/info`, params);
  },
  getWXAcode(params) {
    return getData(`${API_URL}/api/weixin/wxacodeunlimit`, params);
  },
};
